package gameLogic

import (
	"encoding/json"
	redisgw "fronter/redisGw"

	"github.com/sirupsen/logrus"
)

/*
	登录接口
	目前暂时用redis糊一个，肯定会有并发覆盖的问题，后面再看下吧
*/
var LoginSucc int32 = 0
var LoginFailed int32 = 1

func getUser2IdKey(name string) string {
	return "name_" + name + "_uid"
}
func getAllUserMapKey() string {
	return "all_user_map"
}
func getUidKey() string {
	return "uid_auto_key"
}

func LoginImpl(name string, pwd string) int32 {
	res := redisgw.Get(getUser2IdKey(name))
	if res == nil {
		return LoginFailed
	}
	uid := res //先拿到uid
	res = redisgw.HGet(getAllUserMapKey(), *uid)
	if res == nil {
		return LoginFailed
	}
	userInfoJson := res //拿到用户的json userinfo
	var userInfoObj UserInfo
	err := json.Unmarshal(Str2bytes(*userInfoJson), &userInfoObj)
	if err != nil {
		logrus.Errorln("parse name:", name, " json map failed!")
		return LoginFailed
	}
	if userInfoObj.Pwd != pwd {
		return LoginFailed
	}
	return LoginSucc
}

var RegisterSucc int32 = 0
var RegisterRepeated int32 = 1

func RegisterImpl(name string, pwd string) int32 {
	//先简单的糊一个hset,暂时不考虑重复的情况
	key := getUidKey()
	newerUid := redisgw.IncrBy(key, 1)
	redisgw.Set(getUser2IdKey(name), newerUid)

	var userInfoObj UserInfo
	userInfoObj.Name = name
	userInfoObj.Pwd = pwd
	(&userInfoObj).Init()          //初始化用户属性
	userInfoObj.Props.Attack = 100 //用户攻击默认100

	jsonStrByte, _ := json.Marshal(userInfoObj)
	redisgw.HSet(getAllUserMapKey(), newerUid, Bytes2str(jsonStrByte))
	return RegisterSucc
}

func GetAllUser() map[string]UserInfo {
	key := getAllUserMapKey()
	allUserJson := redisgw.HGetall(key)
	//在这里就转回Struct
	var allUserInfo map[string]UserInfo = make(map[string]UserInfo)
	for uid, jsonStr := range allUserJson {
		var userInfo UserInfo
		json.Unmarshal(Str2bytes(jsonStr), &userInfo)
		allUserInfo[uid] = userInfo
	}
	return allUserInfo
}

//更新uid的属性到redis保存
func UpdateUserInfo(uid string, info UserInfo) {
	jsonStr, _ := json.Marshal(info)
	key := getAllUserMapKey()
	redisgw.HSet(key, uid, jsonStr)
}
